<template>
  <div class="container">
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.back()"
      title="小智同学"
    ></van-nav-bar>
    <div class="chat-list" ref="scrollDom">
      <!-- 聊天记录 -->
      <div
        class="chat-item"
        :class="{ left: chat.name === 'xz', right: chat.name === 'self' }"
        v-for="(chat, index) in list"
        :key="index"
      >
        <van-image fit="cover" round :src="Durant" v-if="chat.name === 'xz'" />
        <div class="chat-pao">{{ chat.msg }}</div>
        <van-image fit="cover" round :src="photo" v-if="chat.name === 'self'" />
      </div>
      <!-- <div class="chat-item right">
        <div class="chat-pao">ewqewq</div>
        <van-image fit="cover" round src="https://img.yzcdn.cn/vant/cat.jpeg" />
      </div> -->
    </div>
    <div class="reply-container van-hairline--top">
      <van-field
        v-model="value"
        placeholder="说点什么..."
        ref="focusDom"
        @keyup.enter="send"
      >
        <span @click="send()" slot="button" style="font-size: 12px; color: #999"
          >提交</span
        >
      </van-field>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
// 导入socket的id方法 返回一个socket实例
import io from 'socket.io-client'
import Durant from '@/assets/杜兰特.jpg'
import ouwen from '@/assets/ab2b88f422e4d1785f7f7adb35037b62.jpeg'
export default {
  name: 'user-chat',
  data () {
    return {
      // 小智头像
      Durant,
      ouwen,
      value: '',
      list: [],
      socket: null
    }
  },
  computed: {
    ...mapState('chat', ['photo'])
  },
  methods: {
    // 初始化socket
    initSocket () {
      try {
        // 实例化请求 拿到历史对象
        this.socket = io('http://geek.itheima.net', {
          query: { // 查询参数
            token: this.$store.state.user.token
          },
          transports: ['websocket'] // 传输方式必写
        })
        // 链接成功===>webSocket实例接受请求测试固定connect事件
        this.socket.on('connect', () => {
          console.log('webSocket与服务端链接成功')
          // 小智主动问候用户一次
          this.list.push({ name: 'xz', msg: 'hi :廖sir我是小智!' })
        })
        // 接受服务端发过来的请求 ===>后端人员定义了message事件
        this.socket.on('message', (data) => {
          // console.log('服务端发过来的数据', data) // 先要客服端发送message事件才会让服务端发送请求
          this.list.push({ name: 'xz', msg: data.msg }) // 更新list列表然后渲染DOM页面===>这是异步的!!!!
          // 小智回复完 调用滚动底部事件  ===>小智回复是DOM异步更新===>所有要等DOM节点更新完毕才能执行滚动事件里面的操作
          this.scrollButton()
        })
      } catch (error) {
        console.dir(error)
      }
    },
    send () {
      this.socket.emit('message', { msg: this.value, timestamp: Date.now() })
      // 把用户输入的信息追加到视图中
      this.list.push({ name: 'self', msg: this.value })
      // 每输入发送一次 都要 清空value值
      this.value = ''
      // 输入框自动聚焦===>手动调用focus方法
      this.$refs.focusDom.focus()
    },
    // 当每次小智回复消息都滚到到对应高度
    scrollButton () {
      // 等到异步操作完成才执行===>等list列表渲染完毕后再进行页面滚动(把页面的滚动高度给页面距离顶部的高度)
      this.$nextTick(() => {
        this.$refs.scrollDom.scrollTop = this.$refs.scrollDom.scrollHeight
      })
    }
  },
  created () {
    this.initSocket()
  },
  beforeDestroy () {
    // 性能优化===>关闭webSocket连接
    this.socket.close()
  }
}
</script>

<style scoped lang='less'>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
